package main

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Account struct {
	ID     primitive.ObjectID `bson:"_id"`
	OpenID string             `bson:"open_id"`
}

func insertRows(col *mongo.Collection, c context.Context) {
	many, err := col.InsertMany(c, []interface{}{
		bson.M{
			"open_id": "451512254",
		},
		bson.M{
			"open_id": "41511221554",
		},
	})

	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v", many)
}

func findRow(col *mongo.Collection, c context.Context) {
	find := col.FindOne(c, bson.M{
		"open_id": "4551254",
	})

	var row struct {
		ID     primitive.ObjectID `bson:"_id"`
		OpenID string             `bson:"open_id"`
	}

	err := find.Decode(&row)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%+v", row.ID)

}
func findRows(col *mongo.Collection, c context.Context) {
	cur, err := col.Find(c, bson.M{})
	if err != nil {
		panic(err)
	}
	var accounts []Account
	for cur.Next(c) {
		var row Account
		err := cur.Decode(&row)
		if err != nil {
			panic(err)
		}
		accounts = append(accounts, row)

	}
	fmt.Printf("%+v", accounts)
}

func main() {
	c := context.Background()
	connect, err := mongo.Connect(c, options.Client().ApplyURI("mongodb://admin:123456@localhost:27017")) // 创建连接
	if err != nil {
		panic(err)
	}

	col := connect.Database("coolcar").Collection("account") // 选择数据库
	//insertRows(col, c)
	//findRow(col, c)
	findRows(col, c)
}
